﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BySoft.Web.Utility;
using BySoft.Server.Common;
using BySoft.Server.Consts;
using BySoft.Server.Common.Entity;
using BySoft.Server.Business;
using BySoft.Server.Common.Enum;
using OneSoft.EntityCore;
using System.Web.UI.HtmlControls;
using ZCZP.Web.Site;

namespace BySoft.Web.Site.OutSource
{
    public partial class DeliveryOrderAdd : AuthBasePage
    {
        #region 属性定义
        private string m_strsequenceName = "BsDeliveryOrder" + DateTime.Now.ToString("yyyyMMdd");
        private string m_strTbl = "BS_DeliveryOrder";
        private string m_strMainKey = "BillID";
        private bool m_IsNew = true;

        private DataTable DtDeliveryOrderData
        {
            get
            {
                if (null == Session["DeliveryOrderData"])
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["DeliveryOrderData"];
                }
            }
            set
            {
                Session["DeliveryOrderData"] = value;
            }
        }

        private DataTable CreateDT()
        {
           
            return  BsDeliveryorder.CreateDetailDT();
        }
        #endregion

        #region 初始化及绑定控件
        private void InitData()
        {
            DtDeliveryOrderData = null;
            SetControlAttr(new BsDeliveryorderEntity(), tBase);
            lblBillID.Text = ClsComm.GetBillCode(m_strTbl, m_strMainKey, "PD" + DateTime.Now.ToString("yyMMdd"), 3);
            lblBillDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

            UIHelper.BindEmptyGridView(grdResult, CreateDT());
        }
        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grdResult.Style.Add("word-break", "keep-all");
                grdResult.Style.Add("word-wrap", "normal");
                InitData();
                
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.Page, "Refreashtab();");
        }


           

        private void GetGridViewData()
        {
            DataTable dttemp = CreateDT();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                Label lblDetailID = gvr.FindControl("lblDetailID") as Label;
                  TextBox txtNum = gvr.FindControl("txtNums") as TextBox;
 
                Label lblProductID = gvr.FindControl("lblProductID") as Label;
                Label lblPrice = gvr.FindControl("lblPrice") as Label;
 
                //if (lblProductID == null || string.IsNullOrEmpty(lblProductID.Text.Replace("&nbsp;", "")))
                //{
                //    continue;
                //}
              
                DataRow row = dttemp.NewRow();
                row["DetailID"] = GetGridViewString(lblDetailID);
                row["ProductID"] = GetGridViewString(lblProductID);
                decimal nums = CommonMethod.ConvertToDecimal(txtNum.Text, 2);
                row["Nums"] = nums;
                decimal price = CommonMethod.ConvertToDecimal(lblPrice.Text, 6);
                row["Amount"] = Math.Round(nums * price, 2);
             
                dttemp.Rows.Add(row);
            }
            dttemp.AcceptChanges();
            DtDeliveryOrderData = dttemp;
        }


        private void BindData()
        {
           
            DataView dv = new DataView(DtDeliveryOrderData);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["DetailID"] = index;
                    index++;
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }

            UIHelper.RunScript(this.Page, "Refreashtab();");
        }
        protected void btnAddh_Click(object sender, EventArgs e)
        {
            BindData();
        }
      

       

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }

            BsDeliveryorderEntity entity = new BsDeliveryorderEntity();
            entity.CustomerID=GetString(txtCustomerID) ;

            entity.BillDate = GetDateTime(lblBillDate);
            entity.BillID = GetString(lblBillID);
            entity.Status = "1";
            entity.CreateUserID = CurrentUser.UserID;
            entity.CreateUserName = CurrentUser.UserName;
            entity.CreateDate = DateTime.Now;
            GetGridViewData();

            BsDeliveryorder.SaveOrUpdate(entity, DtDeliveryOrderData,m_IsNew);
            base.LogAction(BaseEnum.ActionType.Add, entity.BillID, true, null, new EntityBase[] { entity });
            DtDeliveryOrderData = null;
            UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../ProductStock/DeliveryOrderList.aspx");
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                string str = e.CommandArgument.ToString();
                int iDel = CommonMethod.ConvertToInt(str);
               // GetGridViewData();
                DataTable dt = DtDeliveryOrderData.Copy();
                dt.Rows.RemoveAt(iDel);
                DtDeliveryOrderData = dt.Copy();
                BindData();
                UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete +

        "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion

              
            }
        }

      
        
        #endregion

        #region 本地方法 ValidateData
        private bool ValidateData()
        {
            string strMention = "";


            if (m_IsNew &&ClsComm.CheckExist(m_strTbl, m_strMainKey, lblBillID.Text.Trim(), true))
                {
                    strMention += "表单号码已经存在！<br />";
                }

                GetGridViewData();

                DataTable dt = DtDeliveryOrderData;
                decimal sum = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    sum +=CommonMethod.ConvertToDecimal(dr["Nums"]);
                }
                if (sum<=0)
                {
                    strMention += "数量不可为空！<br />";
                }
               
            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }
        #endregion


    }
}

